package com.wxscrmplus.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.wxscrmplus.common.core.domain.entity.SysUser;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.exception.ServiceException;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.customer.domain.Customer;
import com.wxscrmplus.customer.domain.FollowUser;
import com.wxscrmplus.customer.domain.bo.FollowUserBo;
import com.wxscrmplus.customer.domain.vo.CustomerVo;
import com.wxscrmplus.customer.domain.vo.FollowUserVo;
import com.wxscrmplus.customer.mapper.CustomerMapper;
import com.wxscrmplus.customer.mapper.FollowUserMapper;
import com.wxscrmplus.customer.service.IFollowUserService;
import com.wxscrmplus.drainage.domain.vo.DraChannelVo;
import com.wxscrmplus.drainage.mapper.DraChannelMapper;
import com.wxscrmplus.statistics.service.IChannelStatsService;
import com.wxscrmplus.system.mapper.SysUserMapper;
import com.wxscrmplus.system.service.ISysUserService;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.external.WxCpUpdateRemarkRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * 跟进成员Service业务层处理
 *
 * @author 王永超
 * @date 2023-03-25
 */
@RequiredArgsConstructor
@Service
public class FollowUserServiceImpl extends WxCpServiceFactory implements IFollowUserService {

    private final FollowUserMapper baseMapper;
    private final CustomerMapper customerMapper;
    private final ISysUserService userService;
    private final SysUserMapper userMapper;
    private final DraChannelMapper channelMapper;
    private final IChannelStatsService channelStatsService;


    /**
     * 查询跟进成员列表
     */
    @Override
    public TableDataInfo<FollowUserVo> queryPageList(FollowUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FollowUser> lqw = buildQueryWrapper(bo);
        Page<FollowUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (FollowUserVo record : result.getRecords()) {
            SysUser sysUser = userMapper.selectById(record.getUserId());
            record.setUserNickName(sysUser.getNickName());
            DraChannelVo draChannelVo = channelMapper.selectVoById(record.getChannelId());
            if (ObjectUtil.isNotNull(draChannelVo)) {
                record.setChannelName(draChannelVo.getName());
            }
        }
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<FollowUser> buildQueryWrapper(FollowUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FollowUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCustomerId() != null, FollowUser::getCustomerId, bo.getCustomerId());
        lqw.eq(bo.getUserId() != null, FollowUser::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getRelType()), FollowUser::getRelType, bo.getRelType());
        lqw.eq(bo.getChannelId() != null, FollowUser::getChannelId, bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getDelType()), FollowUser::getDelType, bo.getDelType());
        lqw.like(StringUtils.isNotBlank(bo.getDescription()), FollowUser::getDescription, bo.getDescription());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), FollowUser::getRemark, bo.getRemark());
        lqw.like(StringUtils.isNotBlank(bo.getRemarkCorpName()), FollowUser::getRemarkCorpName, bo.getRemarkCorpName());
        lqw.like(CollectionUtil.isNotEmpty(bo.getRemarkMobiles()), FollowUser::getRemarkMobiles, bo.getRemarkMobiles());
        lqw.eq(StringUtils.isNotBlank(bo.getQwAddWay()), FollowUser::getQwAddWay, bo.getQwAddWay());
        lqw.eq(StringUtils.isNotBlank(bo.getQwOperUserid()), FollowUser::getQwOperUserid, bo.getQwOperUserid());
        lqw.eq(StringUtils.isNotBlank(bo.getFollowStage()), FollowUser::getFollowStage, bo.getFollowStage());
        lqw.in(FollowUser::getDelType, Arrays.asList(FollowUser.DelTypeFieldEnums.ZERO.getValue(), FollowUser.DelTypeFieldEnums.ONE.getValue()));
        lqw.orderByDesc(FollowUser::getFollowId);
        return lqw;
    }

    /**
     * 修改跟进成员
     */
// d657b6847b1231dc28127a572bfbb658
    @Override
    public Boolean updateByBo(FollowUserBo bo) {
        FollowUser update = BeanUtil.toBean(bo, FollowUser.class);
        validEntityBeforeSave(update);
        String remarkMobiles = bo.getRemarkMobilesStr();
        if (StrUtil.isNotBlank(remarkMobiles)) {
            update.setRemarkMobiles(Arrays.asList(remarkMobiles.split(",")));
        } else {
            update.setRemarkMobiles(new ArrayList<>());
        }
        CustomerVo customerVo = customerMapper.selectVoById(bo.getCustomerId());
        if (Customer.EntryTypeFieldEnums.ONE.getValue().equals(customerVo.getEntryType())) {
            //企微客户，更新企微信息
            WxCpUpdateRemarkRequest wxCpUpdateRemarkRequest = new WxCpUpdateRemarkRequest();
            wxCpUpdateRemarkRequest.setUserId(userService.selectUserNameById(bo.getUserId()));
            wxCpUpdateRemarkRequest.setExternalUserId(customerVo.getQwExternalUserid());
            wxCpUpdateRemarkRequest.setRemark(bo.getRemark());
            wxCpUpdateRemarkRequest.setDescription(bo.getDescription());
            if (CollUtil.isNotEmpty(update.getRemarkMobiles())) {
                Object[] mobile = update.getRemarkMobiles().toArray();
                wxCpUpdateRemarkRequest.setRemarkMobiles((String[]) mobile);
            }
            wxCpUpdateRemarkRequest.setRemarkCompany(bo.getRemarkCorpName());
            try {
                getExternalContactService().updateRemark(wxCpUpdateRemarkRequest);
            } catch (WxErrorException e) {
                throw new ServiceException(e.getMessage());
            }
        }
        channelStatsService.refreshTotalCustomer(update.getChannelId());
        if (ObjectUtil.isNotEmpty(update.getChannelId())) {
            FollowUserVo followUserVo = baseMapper.selectVoById(update.getFollowId());
            if (ObjectUtil.isEmpty(followUserVo.getChannelId())) {
                DraChannelVo draChannelVo = channelMapper.selectVoById(update.getChannelId());
                update.setWinCost(draChannelVo.getCost());
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FollowUser entity) {
        //TODO 做一些数据校验,如唯一约束
    }


}
